package com.xz.xzmybatisagent;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "queryCursor", args = {MappedStatement.class, Object.class, RowBounds.class}),
})
public class MySqlLogInterceptor implements Interceptor {
    private static MySqlLogInterceptor instance;
    private final SqlSender sqlSender;
    private static final Map<Class<? extends java.time.temporal.TemporalAccessor>, DateTimeFormatter> JAVA_TIME_FORMATTERS = new HashMap<>();
    private static final Map<Class<? extends java.time.temporal.TemporalAccessor>, String> JAVA_TIME_PATTERNS = new HashMap<>();
    private static final Map<Class<? extends java.util.Date>, SimpleDateFormat> JAVA_UTIL_DATE_FORMATTERS = new HashMap<>();
    private static final Map<Class<? extends java.util.Date>, String> JAVA_UTIL_DATE_PATTERNS = new HashMap<>();

    static {
        JAVA_TIME_PATTERNS.put(LocalDate.class, "yyyy-MM-d");
        JAVA_TIME_PATTERNS.put(LocalTime.class, "HH:mm:ss");
        JAVA_TIME_PATTERNS.put(LocalDateTime.class, "yyyy-MM-dd HH:mm:ss");

        JAVA_UTIL_DATE_PATTERNS.put(java.util.Date.class, "yyyy-MM-dd HH:mm:ss");
        JAVA_UTIL_DATE_PATTERNS.put(java.sql.Date.class, "yyyy-MM-dd");
        JAVA_UTIL_DATE_PATTERNS.put(java.sql.Time.class, "HH:mm:ss");
        JAVA_UTIL_DATE_PATTERNS.put(java.sql.Timestamp.class, "yyyy-MM-dd HH:mm:ss");
    }

    private MySqlLogInterceptor(int port) {
        // 创建 SqlSender 实例
        this.sqlSender = new SqlSender(port);

        JAVA_TIME_PATTERNS.forEach((clazz, pattern) -> JAVA_TIME_FORMATTERS.put(clazz, DateTimeFormatter.ofPattern(pattern)));
        JAVA_UTIL_DATE_PATTERNS.forEach((clazz, pattern) -> JAVA_UTIL_DATE_FORMATTERS.put(clazz, new SimpleDateFormat(pattern)));
    }

    public static MySqlLogInterceptor getInstance(int port) {
        if (instance == null) {
            instance = new MySqlLogInterceptor(port);
        }
        return instance;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        SqlVo sqlVo = new SqlVo();
        try {
            // 从拦截器参数中获取 MappedStatement（包含SQL映射信息）和参数对象
            MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
            Object parameter = invocation.getArgs()[1];
            // 获取绑定的SQL对象（包含原始SQL和参数信息）
            BoundSql boundSql = ms.getBoundSql(parameter);

            // 获取MyBatis配置
            Configuration configuration = ms.getConfiguration();

            String runSql = getRunSql(configuration, boundSql);

            // 执行SQL语句并获取执行时间
            long start = System.currentTimeMillis();
            Object proceedResult = invocation.proceed();
            long end = System.currentTimeMillis();

            sqlVo.setStatus(true);
            sqlVo.setSqlId(ms.getId());
            sqlVo.setResource(ms.getResource());
            sqlVo.setDatabaseId(ms.getDatabaseId());
            sqlVo.setExecuteTime(end - start);
            sqlVo.setOriginalSql(boundSql.getSql());
            sqlVo.setExecuteSql(runSql);

            String jsonStr = MyJsonUtil.convertObjectToJson(sqlVo);
            // 将SQL语句发送到指定的端口
            this.sqlSender.sendSql(jsonStr);
            // 返回执行结果
            return proceedResult;
        } catch (Throwable t) {
            // 将异常信息发送到指定的端口
            try {

                sqlVo.setStatus(false);
                sqlVo.setMessage(t.getMessage());
                String jsonStr = MyJsonUtil.convertObjectToJson(sqlVo);

                this.sqlSender.sendSql(jsonStr);
            } catch (Exception ignore) {
                // ignore
                System.err.println("Exception while sending sql : " + t.getMessage());
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    private String replaceFirstPlaceholder(String sql, String replacement) {
        // 每次调用，将第一个匹配的？占位符替换为 replacement
        Pattern pattern = Pattern.compile("\\?(?=(?:[^']|'[^']*')*+$)");
        return pattern.matcher(sql).replaceFirst(Matcher.quoteReplacement(replacement));
    }

    private String replacePlaceholder(String sql, Object value) {
        if (value == null) {
            return replaceFirstPlaceholder(sql, "NULL");
        } else if (value instanceof String) {
            value = String.format("'%s'", value);
        } else if (value instanceof Date) {
            value = String.format("'%s'", this.formatLegacyDate((Date) value));
        } else if (value instanceof TemporalAccessor) {
            value = String.format("'%s'", this.formatTemporal((TemporalAccessor) value));
        }
        return replaceFirstPlaceholder(sql, value.toString());
    }

    private String getRunSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
        String sql = boundSql.getSql();
        if (Objects.nonNull(parameterObject) && Objects.nonNull(parameterMappingList) && !parameterMappingList.isEmpty()) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = replacePlaceholder(sql, parameterObject);
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappingList) {
                    String parameterName = parameterMapping.getProperty();
                    Object parameterValue = "-----";
                    if (metaObject.hasGetter(parameterName)) {
                        parameterValue = metaObject.getValue(parameterName);
                    } else if (boundSql.hasAdditionalParameter(parameterName)) {
                        parameterValue = boundSql.getAdditionalParameter(parameterName);
                    }
                    sql = replacePlaceholder(sql, parameterValue);
                }
            }
        }
        return sql;
    }

    // java.time 包下的日期时间类型格式化
    private String formatTemporal(TemporalAccessor ta) {
        try {
            System.out.println(ta.getClass());
            DateTimeFormatter formatter = JAVA_TIME_FORMATTERS.getOrDefault(ta.getClass(), DateTimeFormatter.ISO_DATE_TIME);
            return formatter.format(ta);
        } catch (Throwable e) {
            return ta.toString(); // 格式不兼容时的降级处理
        }
    }

    // java.util 包下的日期时间类型格式化
    private String formatLegacyDate(Date date) {
        try {
            return JAVA_UTIL_DATE_FORMATTERS.get(date.getClass()).format(date);
        } catch (Throwable e) {
            return date.toString();
        }
    }
}